// Command recorder for tracking Python commands
// This allows replaying commands when the kernel restarts

interface RecordedCommand {
  kernelId: string;
  command: string;
  timestamp: number;
}

const commandHistory: RecordedCommand[] = [];

/**
 * Record a Python command for potential replay
 */
export const record = (kernelId: string, command: string): void => {
  commandHistory.push({
    kernelId,
    command,
    timestamp: Date.now(),
  });
};

/**
 * Get all commands for a specific kernel
 */
export const getCommands = (kernelId: string): string[] => {
  return commandHistory
    .filter((cmd) => cmd.kernelId === kernelId)
    .map((cmd) => cmd.command);
};

/**
 * Replay all commands for a kernel
 */
export const replayAll = async (kernelId: string): Promise<void> => {
  const commands = getCommands(kernelId);
  // Import the exec function
  const { execPythonMessage } = await import('./GeppettoJupyterUtils');
  
  for (const command of commands) {
    try {
      await execPythonMessage(command, undefined, false); // Don't record during replay
    } catch (error) {
      console.error(`Error replaying command: ${command}`, error);
    }
  }
};

/**
 * Clear command history for a kernel
 */
export const clearHistory = (kernelId: string): void => {
  const index = commandHistory.findIndex((cmd) => cmd.kernelId === kernelId);
  if (index !== -1) {
    commandHistory.splice(index);
  }
};

export default { record, getCommands, replayAll, clearHistory };

